package com.example.springbootdemo.service;

import com.example.springbootdemo.model.ChooseDataInfo;
import com.example.springbootdemo.model.ChooseInfo;
import com.example.springbootdemo.util.LocalDateTimeUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.*;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.atomic.LongAdder;

@Slf4j
@Service
public class StatisticService {


    private List<String> statisticEle = new ArrayList<>() {{
        add("A");
        add("B");
        add("C");
        add("D");
    }};

    /**
     * 选择操作
     * @param ip ip
     * @param choose 选择结果
     * @return null 表示第一次访问，选择成功；否则返回上次选择的结果
     */
    public ChooseInfo statistic(String ip, String choose) {
        Map<String, ChooseInfo> chooseMap = ChooseDataInfo.getChooseMap();
        Map<String, LongAdder> statisticMap = ChooseDataInfo.getStatisticMap();
        ChooseInfo chooseInfo = new ChooseInfo(choose, ip, LocalDateTimeUtil.getLocalDateTime(LocalDateTime.now()));
        ChooseInfo chooseMapResult = chooseMap.putIfAbsent(ip, chooseInfo);
        if (chooseMapResult == null) {
            // 表示是第一次访问
            LongAdder longAdder = statisticMap.computeIfAbsent(choose, k -> new LongAdder());
            longAdder.increment();

            return null;
        }
        log.info("ip:{} - 已经选择过了", ip);
        return chooseMapResult;
    }

    /**
     * 获取统计结果
     */
    public Map<String, Long> getStatistic() {
        Map<String, LongAdder> statisticMap = ChooseDataInfo.getStatisticMap();

        Map<String, Long> result = new LinkedHashMap<>();
        for (String ele : statisticEle) {
            result.put(ele, statisticMap.get(ele) == null ? 0 : statisticMap.get(ele).longValue());
        }
        return result;
    }
}
